<script setup>
	import {
		ref,
		onMounted,
		computed,
		watch
	} from 'vue'
	import {
		orderStore,
		orderMsg
	} from '@/stores'

	const store = orderStore()
	const msgStore = orderMsg()

	//展示金额
	const showPrice = ref(false)
	const isShow = ref(false)

	//拼车包车存储
	const activeIndex = ref(0)
	const selectIndex = ref('拼车')
	//乘车人数存储
	const activeItem = ref(0)
	const selectItem = ref(1)
	//车型存储
	const activeType = ref(0)
	const selectType = ref('五座车')
	//备注存储
	const activeRemark = ref(null)
	const selectRemark = ref('')
	//备注其他存储
	const testText = ref('')

	//数据
	const carWay = ref(['拼车', '包车'])
	const personNum = ref([1, 2, 3, 4])
	const carType = ref(['五座车', '七座车'])
	const remarkData = ref(['有婴儿', '有老人', '有大件行李', '请准时来接', '请提前联系我', '其他'])

	//经纬度数据存储
	const coordinateData = ref({
		startLat: 0,
		startLng: 0,
		endLat: 0,
		endLng: 0
	})

	// 临时存储选择
	const tempTime = ref('')
	const newTime = ref('')
	const finallyTime = ref('')
	//popup指向
	const carPopup = ref(null)
	const timePopup = ref(null)
	const remarkPopup = ref(null)

	const currentOrder = computed(() => msgStore.currentOrder)
	//处理拼车还是包车
	const handleWayClick = (index, item) => {
		activeIndex.value = index
		selectIndex.value = item
	}
	//处理人数
	const handleCarClick = (index, item) => {
		activeItem.value = index
		selectItem.value = item
	}
	//处理车型
	const handleTypeClick = (index, item) => {
		activeType.value = index
		selectType.value = item
	}
	//处理备注
	const handleRemarkClick = (index, item) => {
		activeRemark.value = index
		selectRemark.value = item
		if (selectRemark.value === '其他') {
			isShow.value = true
			selectRemark.value = testText.value
		}
	}
	//重新选择
	const reSelect = (type) => {
		switch (type) {
			case 'time':
				timePopup.value.open()
				break
			case 'car':
				carPopup.value.open()
				break
			case 'remark':
				remarkPopup.value.open()
				break
		}
	}
	//时间加1
	const addOneTime = (time) => {
		const hour = +time.substring(0, 2) + 1
		const min = time.substring(3)
		newTime.value = hour + ':' + min
	}
	// 时间选择处理
	const handleTimeChange = (e) => {
		tempTime.value = e.detail.value
		addOneTime(tempTime.value)
		finallyTime.value = tempTime.value + '-' + newTime.value
	}
	//时间确认
	const confirmTime = () => {
		msgStore.updateMessage('time', finallyTime.value)
		timePopup.value.close()
		// 如果拼/包车未选择，继续下一步
		if (!currentOrder.value.way) {
			setTimeout(() => {
				carPopup.value.open()
			}, 300)
		}
	}
	//车型和人数确认
	const confirmCar = () => {
		msgStore.updateMessage('way', selectIndex.value)
		if (selectIndex.value === '拼车') {
			msgStore.updateMessage('store', selectItem.value)
		} else {
			msgStore.updateMessage('store', selectType.value)
		}

		//显示价钱
		if (currentOrder.value.way && currentOrder.value.store) {
			showPrice.value = true
		}
		carPopup.value.close()

		// 如果备注未选，继续下一步
		if (!currentOrder.value.remark) {
			setTimeout(() => {
				remarkPopup.value.open()
			}, 300)
		}
	}
	//备注确认
	const confirmRemark = () => {
		if (testText.value) {
			msgStore.updateMessage('remark', testText.value)
		} else {
			msgStore.updateMessage('remark', selectRemark.value)
		}
		remarkPopup.value.close()
	}
	//获取storage
	const getStorage = () => {
		const start = msgStore.selectStartAddress
		const end = msgStore.selectEndAddress
		// msgStore.updateMessage('startAddress', start.address)
		// msgStore.updateMessage('endAddress', end.address)
		coordinateData.value = {
			startLat: start.latitude || 0,
			startLng: start.longitude || 0,
			endLat: end.latitude || 0,
			endLng: end.longitude || 0
		}
	}
	//封装deg2rad函数
	const deg2rad = (deg) => {
		return deg * (Math.PI / 180)
	}
	//封装计算距离函数
	const getDistance = (lat1, lng1, lat2, lng2) => {
		const R = 6371
		const dLat = (lat2 - lat1) * Math.PI / 180
		const dLng = (lng2 - lng1) * Math.PI / 180

		const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
			Math.cos(lat1 * Math.PI / 180) *
			Math.cos(lat2 * Math.PI / 180) *
			Math.sin(dLng / 2) * Math.sin(dLng / 2)
		const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
		return parseFloat((R * c).toFixed(2))
	}
	//预约车
	const orederCar = () => {
		// uni.removeStorageSync('startAddress')
		// uni.removeStorageSync('endAddress')
		store.putOrder(currentOrder.value)
		uni.navigateTo({
			url: '/pages/order/orderDetail?index=0'
		})
	}
	//返回上一页
	const back = () => {
		msgStore.resetCurrentOrder()
		uni.switchTab({
			url: '/pages/home/home'
		})
	}
	onMounted(() => {
		getStorage()
		setTimeout(() => {
			totalDistance()
			timePopup.value.open()
		}, 300)
	})
	//调用计算距离函数
	const totalDistance = () => {
		return getDistance(
			coordinateData.value.startLat,
			coordinateData.value.startLng,
			coordinateData.value.endLat,
			coordinateData.value.endLng
		)
	}
	const totalFare = computed(() => {
		//起步价（小于1公里）
		const startPrice = 8
		//每公里单价（不足一公里按一公里算）
		const singlePrice = 2
		const distance = totalDistance()
		if (distance <= 0) {
			return 0
		}
		let price = startPrice
		if (distance > 1) {
			price += Math.ceil(distance - 1) * singlePrice
		}
		if (currentOrder.value.way === '包车') {
			price += 10
		} else if (!currentOrder.value.way) {
			console.log('未选择拼车/包车')
		}
		return price
	})
	//监听车费
	watch(totalFare, (newVal) => {
		msgStore.updateMessage('totalPrice', newVal)
	}, {
		immediate: true
	})
</script>

<template>
	<uni-nav-bar dark :fixed="true" background-color="#ffffff" color="black" status-bar left-icon="left" title="确认约车"
		@clickLeft="back" :border="false" />
	<view class="box">
		<view class="smallbox_1 smallbox">
			<view class="point"></view>
			<text>{{currentOrder.startAddress}}</text>
		</view>
		<view class="smallbox_2 smallbox">
			<view class="point"></view>
			<text>{{currentOrder.endAddress}}</text>
		</view>
		<view class="smallbox_3">
			<view class="depart" @click="reSelect('time')">
				<image src="/static/images/my.png" />
				<text v-if="currentOrder.time" @click="reSelect('time')">{{currentOrder.time}}出发</text>
				<text v-else>出发时间</text>
			</view>
			<view class="state" @click="reSelect('car')">
				<view class="status">
					<image src="/static/images/my.png" />
					<text v-if="currentOrder.store">{{currentOrder.store}}人</text>
					<text v-else>1人</text>
				</view>
				<text class="pattern" v-if="currentOrder.way">{{currentOrder.way}}</text>
				<text class="pattern" v-else>拼车</text>
			</view>
		</view>
		<view class="smallbox_4">
			<view class="remark" @click="reSelect('remark')">
				<image src="/static/images/my.png" />
				<text v-if="currentOrder.remark">{{currentOrder.remark}}</text>
				<text v-else>备注</text>
			</view>
		</view>
	</view>
	<view class="price" v-if="showPrice">
		预估<text>{{totalFare}}</text>元
	</view>
	<view class="orderCar">
		<button @click="orederCar">预约用车</button>
	</view>
	<!-- 时间 -->
	<uni-popup ref="timePopup" type="bottom">
		<view class="popup-content">
			<text class="popup-title">选择出发时间</text>
			<picker mode="time" @change="handleTimeChange">
				<view class="picker">当前选择: {{ finallyTime || '请选择时间' }}
				</view>
			</picker>
			<button @click="confirmTime" class="confirm-btn">确认</button>
		</view>
	</uni-popup>
	<!-- 人和车型 -->
	<uni-popup ref="carPopup" type="bottom">
		<view class="popup-content">
			<text class="popup-title">拼/包车</text>
			<view class="car">
				<text v-for="(item,index) in carWay" :key="index" @click="handleWayClick(index,item)"
					:class="{active:activeIndex===index}">{{item}}</text>
			</view>
			<view class="share" v-if="activeIndex===0">
				<text class="num">请选择乘车人数</text>
				<text class="tip">儿童、婴幼儿需计乘车人数</text>
				<view class="part">
					<text v-for="(item,index) in personNum" :key="index" :class="{active:activeItem===index}"
						@click="handleCarClick(index,item)">{{item}}</text>
				</view>
			</view>
			<view class="chartered" v-else>
				<text class="model">请选择乘车车型</text>
				<text class="tip">不同车型价格不一样</text>
				<view class="part">
					<text v-for="(item,index) in carType" :key="index" :class="{active:activeType===index}"
						@click="handleTypeClick(index,item)">{{item}}</text>
				</view>
			</view>
			<button @click="confirmCar" class="confirm-btn">确认</button>
		</view>
	</uni-popup>
	<!-- 备注 -->
	<uni-popup ref="remarkPopup" type="bottom">
		<view class="popup-content">
			<text class="popup-title">输入备注信息</text>
			<view class="mark">
				<text v-for="(item,index) in remarkData" :key="index" :class="{active:activeRemark===index}"
					@click="handleRemarkClick(index,item)">{{item}}</text>
				<textarea @blur="bindTextAreaBlur" auto-height v-model="testText" v-if="isShow" />
			</view>
			<button @click="confirmRemark" class="confirm-btn">确认</button>
		</view>
	</uni-popup>
</template>

<style lang="scss" scoped>
	@import "../../styles/_rpx.scss";

	.box {
		display: flex;
		flex-direction: column;
		width: rpx(343);
		height: rpx(156);
		margin: 0 auto;
		border-radius: rpx(5);
		background-color: #ffffff;

		.point {
			width: rpx(7);
			height: rpx(7);
			margin: auto rpx(5) auto rpx(12);
			border-radius: rpx(10);
		}

		.smallbox {
			display: flex;
			width: rpx(325);
			height: rpx(30);
			line-height: rpx(30);

			text {
				font-size: rpx(14);
				font-weight: bold;
			}
		}
	}

	.smallbox_1 {
		margin: rpx(12) auto;
		background-color: #f3f4f8;

		.point {
			background-color: #35ac91;
		}
	}

	.smallbox_2 {
		margin: 0 auto;
		background-color: #f3f4f8;

		.point {
			background-color: #fb5d00;
		}
	}

	.smallbox_3 {
		display: flex;
		margin: rpx(12) 0 0 rpx(18);

		image {
			width: rpx(12) !important;
			height: rpx(12) !important;
			vertical-align: middle;
			margin-right: rpx(10);
		}

		text {
			font-size: rpx(12);
			color: #d0d1d2;
		}

		.depart {
			line-height: rpx(16);
		}

		.state {
			display: flex;
			gap: rpx(15);
			margin-left: rpx(30);

			.status {
				line-height: rpx(16);
			}

			.pattern {
				display: flex;
				width: rpx(38);
				height: rpx(16);
				font-size: rpx(12);
				margin: auto 0;
				justify-content: center;
				vertical-align: middle;
				align-items: center;
				align-content: center;
				color: #eda64d;
				background-color: #fcf6e9;
			}
		}
	}

	.smallbox_4 {
		line-height: rpx(12);

		image {
			width: rpx(12) !important;
			height: rpx(12) !important;
			margin-right: rpx(10);
			vertical-align: middle;
		}

		text {
			font-size: rpx(12);
			color: #d0d1d2;
		}

		margin: rpx(18) 0 0 rpx(18);
	}

	.orderCar {
		position: fixed;
		bottom: rpx(10);
		left: 50%;
		transform: translateX(-50%);

		button {
			position: relative;
			width: rpx(345);
			height: rpx(42);
			line-height: rpx(42);
			background-color: #52c582;
			border: rpx(1) solid #fffdff;
			font-size: rpx(14);
			color: white;
			margin: 0 auto;
		}
	}

	.price {
		position: fixed;
		bottom: rpx(60);
		left: 50%;
		transform: translateX(-50%);

		text {
			font-size: rpx(20);
			margin: 0 rpx(5);
			color: #00770a;
		}
	}

	// popup样式
	.popup-content {
		.active {
			background-color: #52c582;
			color: white;
		}

		.tip {
			font-size: rpx(14);
			color: #75747b;
		}

		.car {
			display: flex;
			gap: rpx(15);

			text {
				width: rpx(75);
				height: rpx(33);
				line-height: rpx(33);
				text-align: center;
				border: rpx(1) solid #e3e8ec;
			}
		}

		.part {
			display: flex;
			gap: rpx(15);

			text {
				text-align: center;
				border: rpx(1) solid #e3e8ec;
			}
		}

		.share {
			display: flex;
			flex-direction: column;
			gap: rpx(15);

			.num {
				margin-top: rpx(15);
			}

			.part text {
				width: rpx(44);
				height: rpx(28);
				line-height: rpx(28);
			}
		}

		.chartered {
			display: flex;
			flex-direction: column;
			gap: rpx(15);

			.model {
				margin-top: rpx(15);
			}

			.part text {
				width: rpx(74);
				height: rpx(35);
				line-height: rpx(35);
			}
		}

		.mark {
			display: flex;
			gap: rpx(10);
			flex-wrap: wrap;

			text {
				width: rpx(105);
				height: rpx(30);
				line-height: rpx(30);
				font-size: rpx(14);
				text-align: center;
				border: rpx(1) solid #e3e8ec;
			}

			textarea {
				border: rpx(1) solid black;
				font-size: rpx(14);
				padding: rpx(5);
			}
		}
	}

	.popup-content {
		padding: rpx(20);
		background-color: #fff;
		border-radius: 16px 16px 0 0
	}

	.popup-title {
		font-weight: bold;
		margin-bottom: 15px;
		display: block;
	}

	.confirm-btn {
		margin-top: 20px;
		background-color: #52c582;
		color: white;
	}

	.picker {
		padding: 10px;
		border: 1px solid #eee;
		border-radius: 5px;
		margin: 10px 0;
	}
</style>